package com.scs.application.modules.report.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.query.QueryCondition;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.entity.Dept;
import com.scs.application.modules.base.service.DeptService;
import com.scs.application.modules.base.service.UserWarehouseService;
import com.scs.application.modules.base.vo.UserWarehouseVO;
import com.scs.application.modules.cfg.utils.ParameterUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ Description：报表前置处理方法
 *  一般用作数据权限拼接
 */
@Slf4j
@Component
public class BeforeReport  {

    @Autowired
    UserWarehouseService userWarehouseService;
    @Autowired
    DeptService deptService;

    private static  BeforeReport services;

    @PostConstruct
    public void init() {
        services = this;
        services.userWarehouseService = this.userWarehouseService;
        services.deptService = this.deptService;
    }

    /**
     * @Description： 替换数据源中的  %filterSql%
     */
    public String after(String dataSql,String sqlFilter){
        //管理员不做数据过滤
        System.out.println("UserUtils.currentUser().isAdmin()="+UserUtils.currentUser().isAdmin());
        if(UserUtils.currentUser().isAdmin()) return dataSql.replaceAll("%filterSql%"," ");
        return dataSql.replaceAll("%filterSql%"," "+sqlFilter+" ");
    }


    /**
     * @Description： 获取登录用户所有可用库位
     * @return  null|| 可用库位以,分割的字符串, 'id1','id2'
     */
    public static String getUserWarehouseIds(){
        //登录用户可用工位
        List<UserWarehouseVO> userWarehouseList = BeforeReport.services.userWarehouseService.getUserWarehouse();
        if(userWarehouseList == null || userWarehouseList.size() <1)   return null;

        List<String> ids = new ArrayList<String>();
        userWarehouseList.forEach(userWarehouse -> {
            ids.add("'"+userWarehouse.getWarehouseId()+"'");
        });
        return ids.stream().collect(Collectors.joining(","));
    }

    /**
     * @Description： 获取登录用户所有可用仓库所对应的科室
     * @return  null|| 可用库位以,分割的字符串, 'id1','id2'
     */
    public static String getUserWarehouseByDepts(){
        //登录用户可用工位
        List<UserWarehouseVO> userWarehouseList = BeforeReport.services.userWarehouseService.getUserWarehouse();
//        if(userWarehouseList == null || userWarehouseList.size() <1)   return null;
        //判断该仓库科室下是否包含该人员的科室
        if (!userWarehouseList.stream().filter(w->String.valueOf(w.getDeptId()).equals(UserUtils.currentUser().getDeptId())).findAny().isPresent()){
            UserWarehouseVO us=new UserWarehouseVO();
            us.setDeptId(UserUtils.currentUser().getDeptId());
            userWarehouseList.add(us);
        }
        List<String> ids = new ArrayList<>();
        userWarehouseList.forEach(userWarehouse -> {
            if (StringUtils.isNotBlank(userWarehouse.getDeptId())) {
                ids.add("'"+userWarehouse.getDeptId()+"'");
            }
        });
        return String.join(",", ids);
    }

    /**
     * @Description：  获取登录用户所拥有的his科室代码列表
     */
    public static List<String> getUserDeptCodeHisList(){
        //登录用户可用工位
        List<UserWarehouseVO> userWarehouseList = BeforeReport.services.userWarehouseService.getUserWarehouse();
        List<String> deptIdList = new ArrayList<>();
        if (!userWarehouseList.isEmpty()) {
            deptIdList.addAll(userWarehouseList.stream().map(UserWarehouseVO::getDeptId).collect(Collectors.toList()));
        }
        deptIdList.add(UserUtils.currentUser().getDeptId());
        List<Dept> deptList = BeforeReport.services.deptService.list(Wrappers.<Dept>query().in("id",deptIdList).isNotNull("his_code"));
        if (!deptList.isEmpty()) {
            return deptList.stream().map(Dept::getHisCode).distinct().collect(Collectors.toList());
        }
        return Arrays.asList("-999");
    }


    /**
     * @Description： 获取登录用户所有可用库位
     * @return  null|| 可用库位id集合, id1,id2
     */
    public static List<String> getUserWarehouseIdList(){
        //登录用户可用工位
        List<UserWarehouseVO> userWarehouseList = BeforeReport.services.userWarehouseService.getUserWarehouse();
        if(userWarehouseList == null || userWarehouseList.size() <1)   {
            return  Arrays.asList("-999");
        };

        return userWarehouseList.stream().map(userWarehouse -> userWarehouse.getId()).collect(Collectors.toList());
    }


    /**
     * @Description： 当前登录用户是否有全院查看权限
     * @return  true：管理员或者当前用户所属科室已开启全院数据权限
     */
    public static boolean getFlagAllData(){
        if(UserUtils.currentUser().isAdmin()) return true;
        Dept dept = BeforeReport.services.deptService.getById(UserUtils.currentUser().getDeptId());

        //不允许查看全员数据，则只能看到该用户可用仓库的入库信息
        if (dept.getFlagAllData() == null ||  !dept.getFlagAllData())  return false;
        return true;
    }


    /**
    * @Description： 入库明细报表
    * @Author wyt
    * @Date 2020/10/16
    */
   public String preInOrderItem(String dataSql, LinkedHashMap param){
       String sqlFilter = "";

       //不允许查看全员数据，则只能看到该用户可用仓库的入库信息
       if (!getFlagAllData()) {
           //登录用户可用工位
           String userWarehouseIds = getUserWarehouseIds();
           if(userWarehouseIds == null )  {
               sqlFilter+=" and 1=0 ";
               return after(dataSql,sqlFilter);
           }
           sqlFilter+=" and wwo.warehouse_id in ("+userWarehouseIds+")";

       }
       return after(dataSql,sqlFilter);
   }



    /**
     * @Description： 出库明细和出库汇总报表
     * @Author wyt
     * @Date 2020/10/16
     */
    public String outOrder(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        //不允许查看全员数据，则只能看到本科室
        if (!getFlagAllData()) {
            //登录用户可用工位
            String userWarehouseIds = getUserWarehouseIds();
            if(userWarehouseIds == null )  {
                sqlFilter+=" and 1=0 ";
                return after(dataSql,sqlFilter);
            }
            sqlFilter+=" and wwo.warehouse_id in ( "+userWarehouseIds+" )";

        }
        return after(dataSql,sqlFilter);
    }

    /**
     * @Description： 入库库明细、入库汇总报表、库存明细
     * @Author wyt
     * @Date 2020/10/16
     */
    public String inOrder(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        //不允许查看全员数据，则只能看到本科室
        if (!getFlagAllData()) {
            //登录用户可用工位
            String userWarehouseIds = getUserWarehouseIds();
            if(userWarehouseIds == null )  {
                sqlFilter+=" and 1=0 ";
                return after(dataSql,sqlFilter);
            }
            sqlFilter+=" and tmain.warehouse_id in ( "+userWarehouseIds+" )";

        }
        return after(dataSql,sqlFilter);
    }


    /**
     * @Description： 库存明细报表 库存汇总
     * @Author wyt
     * @Date 2020/10/16
     */
    public String stock(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        //不允许查看全员数据，则只能看到该用户可用仓库的入库信息
        if (!getFlagAllData()) {
            //登录用户可用工位
            String userWarehouseIds = getUserWarehouseIds();
            if(userWarehouseIds == null )  {
                sqlFilter+=" and 1=0 ";
                return after(dataSql,sqlFilter);
            }
            sqlFilter+=" and ws.warehouse_id in ("+userWarehouseIds+")";

        }
        return after(dataSql,sqlFilter);
    }

    /**
     * @Description： 智能柜报表 库存汇总 和明细
     */
    public String fsdTcbstock(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        //不允许查看全员数据，则只能看到该用户可用仓库的入库信息
        if (!getFlagAllData()) {
            //登录用户可用工位
            String userWarehouseIds = getUserWarehouseIds();
            if(userWarehouseIds == null )  {
                sqlFilter+=" and 1=0 ";
                return after(dataSql,sqlFilter);
            }
            sqlFilter+=" and warehouse_id in ("+userWarehouseIds+")";

        }
        return after(dataSql,sqlFilter);
    }

    /**
     * @Description： 科室成本明细 汇总
     * @Author wyt
     * @Date 2020/10/16
     */
    public String deptOutOrder(String dataSql, LinkedHashMap param){
        String sqlFilter = "";
        String flowValue = ParameterUtils.getSystemSettlementFlowValue();
        //不允许查看全员数据，则只能看到本科室
        if (!getFlagAllData()) {
            //登录用户可用工位对应科室
            String userWarehouseByDepts = getUserWarehouseByDepts();
            if (userWarehouseByDepts == null) {
                sqlFilter += " and 1=0 ";
                return after(dataSql, sqlFilter);
            }
            sqlFilter+=" and bill.dept_id in ( "+userWarehouseByDepts+" )";
        }

        return after(dataSql,sqlFilter);
    }

    /**
     * @Description： 请领配送进度报表
     * @Author
     * @Date 2020/10/16
     */
    public String deptApplyStatus(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        //不允许查看全员数据，则只能看到本科室
        if (!getFlagAllData()) {
            //登录用户可用工位对应科室
            String userWarehouseByDepts = getUserWarehouseByDepts();
            if(userWarehouseByDepts == null )  {
                sqlFilter+=" and 1=0 ";
                return after(dataSql,sqlFilter);
            }
            sqlFilter+=" and dept_id in ( "+userWarehouseByDepts+" )";
        }
        return after(dataSql,sqlFilter);
    }

    /**
     * @Description： 病人消耗明细
     */
    public String deptOprtUseDtl(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        String userWarehouseIds = getUserWarehouseIds();

        if (!getFlagAllData()) {
            sqlFilter += " and (dept_id = '" + UserUtils.currentUser().getDeptId() + "' or exec_dept_id = '" + UserUtils.currentUser().getDeptId() + "' or warehouse_id in (" + userWarehouseIds + ")) ";

        }
        return after(dataSql,sqlFilter);
    }

    /**
     * @Description： 科室执行有效计费
     */
    public String deptHisExec(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        String userWarehouseIds = getUserWarehouseIds();

        if (!getFlagAllData()) {
            sqlFilter += " and warehouse_id in (" + userWarehouseIds + ")  ";

        }
        return after(dataSql,sqlFilter);
    }


    /**
     * @Description： 供应商消耗结算汇总，数据源
     */
    public String preSumSpCategory(String dataSql, LinkedHashMap param){
        String sqlFilter = "";
        List<QueryCondition> queryJson = null;
        if (param.get("queryString") != null) queryJson = JSON.parseArray(param.get("queryString")+"", QueryCondition.class);

        String categoryLevel = "1";
        if (queryJson != null) {
            //分类级别
            List<QueryCondition> queryConditionLevels = queryJson.stream().filter(ob -> ob.getField().equalsIgnoreCase("category_level")).collect(Collectors.toList());
            if (queryConditionLevels!= null && queryConditionLevels.size() > 0) categoryLevel=queryConditionLevels.get(0).getVal()+"";
        }
        return dataSql.replaceAll("%category_level%"," "+categoryLevel+" ");
    }

    /**
     * @Description： 供应商消耗结算汇总，列sql
     */
    public String preColumnSqlSumSpCategory(String columnSql, LinkedHashMap param){
        String sqlFilter = "";
        List<QueryCondition> queryJson = null;
        if (param.get("queryString") != null) queryJson = JSON.parseArray(param.get("queryString")+"", QueryCondition.class);

        String categoryLevel = "1";
        if (queryJson != null) {
            //分类级别
            List<QueryCondition> queryConditionLevels = queryJson.stream().filter(ob -> ob.getField().equalsIgnoreCase("category_level")).collect(Collectors.toList());
            if (queryConditionLevels!= null && queryConditionLevels.size() > 0) categoryLevel=queryConditionLevels.get(0).getVal()+"";
        }
        return columnSql.replaceAll("%category_level%"," "+categoryLevel+" ");
    }

    /**
     * @Description： 科室成本明细汇总-耗材
     */
    public String preColumnSqlDeptMatr(String columnSql, LinkedHashMap param){
        String sqlFilter = "";
        List<QueryCondition> queryJson = null;
        if (param.get("queryString") != null) queryJson = JSON.parseArray(param.get("queryString")+"", QueryCondition.class);

        String matrId = "''";
        if (queryJson != null) {
            //分类级别
            List<QueryCondition> queryConditionLevels = queryJson.stream().filter(ob -> ob.getField().equalsIgnoreCase("matr_id")).collect(Collectors.toList());
            if (queryConditionLevels!= null && queryConditionLevels.size() > 0) {
                matrId = queryConditionLevels.get(0).getVal() + "";
                List<String> list = JSON.parseArray(matrId, String.class);
                matrId =  list.stream().collect(Collectors.joining(","));
            }
        }
        return columnSql.replaceAll("%matr_id%"," "+matrId+" ");
    }
    /**
     * @Description： 供应商消耗结算汇总，数据源
     */
    public String preSumDeptMatr(String dataSql, LinkedHashMap param){
        String sqlFilter = "";
        List<QueryCondition> queryJson = null;
        if (param.get("queryString") != null) queryJson = JSON.parseArray(param.get("queryString")+"", QueryCondition.class);

        String matrId = "''";
        if (queryJson != null) {
            //分类级别
            List<QueryCondition> queryConditionLevels = queryJson.stream().filter(ob -> ob.getField().equalsIgnoreCase("matr_id")).collect(Collectors.toList());
            if (queryConditionLevels!= null && queryConditionLevels.size() > 0) {
                matrId = queryConditionLevels.get(0).getVal() + "";
                List<String> list = JSON.parseArray(matrId, String.class);
                matrId =  list.stream().collect(Collectors.joining(","));
            }
        }

        if (!getFlagAllData()) {
            sqlFilter += " and dept_id in ("+getUserWarehouseByDepts()+")  ";
        }
        dataSql = dataSql.replaceAll("%filterSql%"," "+sqlFilter+" ");

        return dataSql.replaceAll("%matr_id%"," "+matrId+" ");
    }
    /**
     * @Description： 科室领用物资分类统计
     */
    public String preDeptBillSumCategory(String dataSql, LinkedHashMap param){
        String sqlFilter = "";
        List<QueryCondition> queryJson = null;
        if (param.get("queryString") != null) queryJson = JSON.parseArray(param.get("queryString")+"", QueryCondition.class);

        String categoryLevel = "1";
        if (queryJson != null) {
            //分类级别
            List<QueryCondition> queryConditionLevels = queryJson.stream().filter(ob -> ob.getField().equalsIgnoreCase("category_level")).collect(Collectors.toList());
            if (queryConditionLevels!= null && queryConditionLevels.size() > 0) categoryLevel=queryConditionLevels.get(0).getVal()+"";
        }
        if (!getFlagAllData()) {
            sqlFilter += " and dept_id in ("+getUserWarehouseByDepts()+")  ";

        }
        return after(dataSql.replaceAll("%category_level%"," "+categoryLevel+" "),sqlFilter);
    }

    /**
     * @Description： 预算预警报表 报表标识【budget_dtl_warn】
     * @Author
     * @Date 2021/06/05
     */
    public String budgetDtlWarn(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        //不允许查看全员数据，则只能看到本科室
        if (!getFlagAllData()) {
            //登录用户可用工位对应科室
            String userWarehouseByDepts = getUserWarehouseByDepts();
            if(userWarehouseByDepts == null )  {
                sqlFilter+=" and 1=0 ";
                return after(dataSql,sqlFilter);
            }
            sqlFilter+=" and dept_id in ( "+userWarehouseByDepts+" )";
        }
        return after(dataSql,sqlFilter);
    }

    /**
     * @Description： 科室领用物资分类统计
     */
    public String preReagentByDept(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        //不允许查看全员数据，则只能看到本科室
        if (!getFlagAllData()) {
            //登录用户可用工位对应科室
            String userWarehouseByDepts = getUserWarehouseByDepts();
            if(userWarehouseByDepts == null )  {
                sqlFilter+=" and 1=0 ";
                return after(dataSql,sqlFilter);
            }
            sqlFilter+=" and tmain.dept_id in ( "+userWarehouseByDepts+" )";
        }
        return after(dataSql,sqlFilter);
    }

    /**
     * @Description： 科室执行有效计费
     */
    public String preReagentByWarehouse(String dataSql, LinkedHashMap param){
        String sqlFilter = "";

        String userWarehouseIds = getUserWarehouseIds();

        if (!getFlagAllData()) {
            sqlFilter += " and tmain.warehouse_id in (" + userWarehouseIds + ")  ";

        }
        return after(dataSql,sqlFilter);
    }
}
